from django.http import JsonResponse
from django.views import View
from django.utils.decorators import method_decorator
from pypinyin import lazy_pinyin
from django_system.role_recognize import check_permission
import django_system.settings
from django.core.paginator import Paginator
from .models import User, Role, Permission
import json
import re
import jwt
from utils.qiniu_manage import QiniuManage
from hashlib import sha256
from zhineng.models import UserInfo
from utils.aliyun_sms_2017 import Sample
from random import randint
from django_system import settings
import redis

r = redis.Redis(host='120.25.166.156', port=6379, password='040908Gds.', decode_responses=True)


def connect_qiniu():
    qn_cli = QiniuManage(settings.AK, settings.SK, settings.BN)
    return qn_cli


class Register(View):
    """获取前端传来的手机号"""

    def post(self, request):
        data = json.loads(request.body)
        phone = data['phone']
        if phone is None:
            return JsonResponse({'msg': "手机号不能为空"}, status=400)
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return JsonResponse({'msg': "手机号格式错误", "status": 400})
        code = ''
        for i in range(4):
            code += str(randint(0, 9))
        samp = Sample()
        resp = samp.main(phone, code)
        if resp.body.code == 'OK':
            r.setex(phone, 60, code)
            return JsonResponse({'code': 200, 'msg': '验证码发送成功', 'data': code})
        else:
            return JsonResponse({'code': 400, 'msg': '验证码发送失败'})


class RoleView(View):
    """添加角色"""

    @method_decorator(check_permission(['管理员']))
    def post(self, request):
        data = json.loads(request.body)
        name = data['name']
        status = data['status']
        permissions = data['permissions']
        if not data.values():
            return JsonResponse({'msg': '前端数据不能为空'}, status=400)
        try:
            role = Role.objects.create(name=name, status=status)
            role.permissions.set(permissions)
            for i in permissions:
                p = Permission.objects.get(id=i)
                role.permissions.add(p)
            return JsonResponse({'msg': '角色添加成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '角色添加失败，原因是%s' % e}, status=500)


class QueryRoleView(View):
    """查询所有角色"""

    @method_decorator(check_permission(['管理员']))
    def get(self, request, p_id, p_num):
        roles = Role.objects.filter(is_delete=False).all().values()
        paginator = Paginator(roles, p_num)
        page = paginator.page(p_id)
        if not roles.values():
            return JsonResponse({'msg': '没有该角色'}, status=400)
        return JsonResponse({'msg': '查看所以角色成功', 'total': len(roles), 'datas': list(page)},
                            status=200, safe=False)


class GetAllRolesView(View):
    def get(self, request):
        roles = list(Role.objects.all().values())
        return JsonResponse({'data': roles, 'code': 200})


class ChangeRoleView(View):
    """修改角色信息"""

    @method_decorator(check_permission(['管理员']))
    def put(self, request, id):
        data = json.loads(request.body)
        name = data['name']
        status = data['status']
        permissions = data['permissions']
        try:
            role = Role.objects.get(id=id)
            Role.objects.filter(id=id).update(name=name, status=status)
            role.permissions.set(permissions)
            for i in permissions:
                p = Permission.objects.get(id=i)
                role.permissions.add(p)
            return JsonResponse({'msg': '修改角色状态成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '修改状态失败%s' % e}, status=500)


class DeleteRoleView(View):
    """删除角色"""

    @method_decorator(check_permission(['管理员']))
    def delete(self, request, id):
        try:
            Role.objects.filter(id=id).update(is_delete=True)
            return JsonResponse({'msg': '角色删除成功'}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '删除失败%s' % e}, status=500)


class PermissionView(View):
    """添加角色以及权限"""

    @method_decorator(check_permission(['管理员']))
    def get(self, request):
        permissions = Permission.objects.all()
        return JsonResponse({'data': list(permissions.values()), 'code': 200, 'msg': '获取成功'})

    def post(self, request):
        data = json.loads(request.body)
        r = data.get('role')
        role = Role.objects.get(id=r)
        if r == 1:
            permission = Permission.objects.all()
            for i in permission:
                role.permissions.add(i)
            return JsonResponse({'msg': 'success', 'code': 200})
        else:
            permissions = data.get('permissions')
            for i in permissions:
                p = Permission.objects.get(id=i)
                role.permissions.add(p)
            return JsonResponse({'msg': 'success', 'code': 200})


# 添加角色权限
class GetAddPermission(View):

    def get(self, request):
        p_id = request.GET.get('p_id')
        p_num = request.GET.get('p_num')
        permissions = Permission.objects.filter(is_delete=False).all().values()
        paginator = Paginator(permissions, p_num)
        page = paginator.page(p_id)
        return JsonResponse({'data': list(page), 'code': 200, 'msg': '获取成功', 'total': len(permissions)})

    @method_decorator(check_permission(['管理员']))
    def post(self, request):
        data = json.loads(request.body)
        r = data.get('role')
        role = Role.objects.get(id=r)
        if r == 1:
            permission = Permission.objects.all()
            for i in permission:
                role.permissions.add(i)
            return JsonResponse({'msg': 'success', 'code': 200})
        else:
            permissions = data.get('permissions')
            for i in permissions:
                p = Permission.objects.get(id=i)
                role.permissions.add(p)

            return JsonResponse({'msg': 'success', 'code': 200})


class MenusView(View):
    def get(self, request, id):
        user = User.objects.get(id=id)
        role = Role.objects.all()
        r_list = list(role.values())
        for i in range(len(role)):
            r_list[i]['permissions'] = list(role[i].permissions.all().values())
        roles = User.objects.get(id=id).roles.all()
        user_all_p = []
        for i in roles:
            for k in i.permissions.all().values():
                user_all_p.append(k)
        for i in r_list:
            for k in i['permissions']:
                if k not in user_all_p:
                    k['status'] = 'disable'
                else:
                    k['status'] = 'enable'
        return JsonResponse({'code': 200, 'data': r_list})


class LoginView(View):
    def post(self, request):
        """登录"""
        # 获取前端传来的账号密码
        data = json.loads(request.body)
        # 校验账号密码
        # 不能为空
        # 获取字典全部的值
        if not data.values():
            return JsonResponse({'msg': '账号密码不能为空', 'code': 400})
        # 账号密码是否符合规范
        name = data.get('name')
        pwd = data.get('pwd')
        # 判断账号密码是否存在
        try:
            user = User.objects.get(username=name)
        except:
            return JsonResponse({'msg': "账号不存在", 'code': 400})
        # 3.账号存在，判断密码，密码正确的登录
        new_pwd = sha256(pwd.encode()).hexdigest()
        if new_pwd != user.password:
            return JsonResponse({'msg': '密码错误', 'code': 401})

        token = jwt.encode({'user': name}, key=django_system.settings.SECRET_KEY)
        role = User.objects.filter(username=name).first().roles.first().name
        return JsonResponse({'msg': '登录成功', 'code': 200, 'token': token, 'role': role})


class UserView(View):
    """获取所有用户及角色"""

    def get(self, request):
        p_id = request.GET.get('p_id', 1)
        p_num = request.GET.get('p_num', 10)
        user_list = User.objects.filter(is_delete=False).all().values()
        paginator = Paginator(user_list, p_num)
        page = list(paginator.page(p_id))
        for i in page:
            i['roles'] = list(User.objects.filter(id=i['id']).first().roles.all().values())
        return JsonResponse(
            {'data': page, 'total': len(list(user_list)), 'code': 200})


class UserInfoView(View):
    """
    根据不同条件查询用户信息
    """

    @method_decorator(check_permission(['管理员']))
    def get(self, request):
        username = request.user
        roles = request.GET.get('roles')
        if username != '' and roles == '':
            user = User.objects.filter(username=username).all().values()
            if user:
                return JsonResponse({'code': 200, 'data': list(user)})
            else:
                return JsonResponse({'code': 400, 'msg': '查找失败'})
        if username == '' and roles != '':
            user_info = []
            user_list = list(User.objects.all().values())
            for i in user_list:
                i['roles'] = list(User.objects.filter(id=i['id']).first().roles.all().values())
                for j in i['roles']:
                    if j['name'] == roles:
                        user_info.append(i)
            return JsonResponse({'msg': 'ok', 'data': user_info}, safe=False)
        else:
            user_info = []
            user_list = list(User.objects.filter(username=username).all().values())
            for i in user_list:
                i['roles'] = list(User.objects.filter(id=i['id']).first().roles.all().values())
                for j in i['roles']:
                    if j['name'] == roles:
                        user_info.append(i)
            return JsonResponse({'msg': 'ok', 'data': user_info}, safe=False)

    @method_decorator(check_permission(['管理员']))
    def post(self, request):
        data = json.loads(request.body)
        username = data['name']
        phone = data['phone']
        roles = data['roles']
        new_pwd = ''.join(lazy_pinyin(username)) + '123456'
        user = User.objects.create(username=username, password=new_pwd, phone=phone)
        user.roles.add(Role.objects.get(id=roles))
        return JsonResponse({'msg': 'ok', 'code': 200}, safe=False)


class UsermanageModel(View):
    ''' 修改和删除用户信息 '''

    @method_decorator(check_permission(['管理员']))
    def put(self, request, id):

        data = json.loads(request.body)
        password = data['password']
        username = data['username']
        phone = data['phone']
        roles = data['roles']
        user = User.objects.filter(id=id).first()
        if not user:
            return JsonResponse({'msg': '用户不存在'}, safe=False)
        try:
            new_pwd = sha256(password.encode()).hexdigest()
            User.objects.filter(id=id).update(password=new_pwd, username=username, phone=phone)
            user.roles.clear()
            user.roles.add(Role.objects.get(id=roles))
            return JsonResponse({'msg': '修改成功', 'code': 200}, safe=False)
        except Exception as e:
            return JsonResponse({'msg': str(e)}, safe=False)

    @method_decorator(check_permission(['管理员']))
    def delete(self, request, id):
        User.objects.filter(id=id).first().update(is_delete=True)
        return JsonResponse({'msg': '删除成功'}, safe=False)


class UserLogin(View):
    def post(self, request):
        data = json.loads(request.body)
        phone = data['phone']
        code = data['code']
        try:
            user = User.objects.get(phone=phone)
        except Exception as e:
            print(e)
            return JsonResponse({'msg': '用户不存在'}, safe=False)
        if r.get(phone):
            if int(code) != int(r.get(phone)):
                return JsonResponse({'msg': '验证码错误', 'code': 302})
            else:
                token = jwt.encode({'user': user.username}, key=django_system.settings.SECRET_KEY)
                return JsonResponse({'msg': '登陆成功', 'code': 200, 'token': token, 'role': user.roles.first().name,
                                     'user': user.username}, status=200)
        else:
            return JsonResponse({'msg': '验证码未发送或已失效', 'code': 301})


class EditOneself(View):
    """
    修改登录用户个人信息
    """

    def get(self, request):
        user = User.objects.filter(username=request.user).first()
        try:
            user_info = UserInfo.objects.get(user=user)
            data = {'username': user.username, 'phone': user.phone, 'number': user_info.number, 'age': user_info.age,
                    'address': user_info.address, 'parents': user_info.parents}
            return JsonResponse({'data': data, 'code': 200, 'msg': '获取成功'})
        except:
            data = {'username': user.username, 'phone': user.phone}
            return JsonResponse({'data': data, 'code': 300, 'msg': '获取成功'})

    def post(self, request):
        data = json.loads(request.body)
        name = request.user
        user = User.objects.filter(username=name).first()
        user_info = UserInfo.objects.filter(user=user).first()
        user.username = data['username']
        user.phone = data['phone']
        if data['password']:
            new_pwd = ''.join(lazy_pinyin(data['username'])) + '123456'
            user.password = new_pwd
        user.save()
        if user_info:
            user_info.number = data['number']
            user_info.age = data['age']
            user_info.address = data['address']
            user_info.parents = data['parents']
            user_info.save()
        else:
            info = UserInfo.objects.create(user=user)
            info.number = data['number']
            info.age = data['age']
            info.address = data['address']
            info.parents = data['parents']
            info.save()
        return JsonResponse({'code': 200, 'msg': '修改成功', 'new_username': user.username})


class ChangeHeadImage(View):
    def get(self, request):
        user = User.objects.filter(username=request.user).first()
        user_info = UserInfo.objects.filter(user=user).first()
        if user_info:
            return JsonResponse({'code': 200, 'msg': '获取成功', 'headImage': user_info.image})
        else:
            return JsonResponse({'code': 201, 'headImage': ''})

    def post(self, request):
        qc = connect_qiniu()
        token = qc.get_token()
        return JsonResponse({'code': 200, 'msg': '获取成功', 'token': token})

    def put(self, request):
        data = json.loads(request.body)
        qc = connect_qiniu()
        key = data['key']
        url = qc.download_file(key)
        user = User.objects.filter(username=request.user).first()
        user_info = UserInfo.objects.filter(user=user).first()
        if user_info:
            user_info.image = url
            user_info.save()
            return JsonResponse({'code': 200, 'msg': '修改成功', 'url': url})
        else:
            return JsonResponse({'code': 301, 'msg': '请先编辑个人信息'})
